<template>
  <div class="home-live-player">
    <!-- 直播权限框 -->
    <div class="unlogin-box frosted-glass" v-if="isLimitFlag">
      <div class="unlogin-container">
        <img src="@/assets/images/live-lock.png" alt="lock" />
        <div class="limit-tips">
          <!-- 未登录 -->
          <template>
            <p class="not-allow">您无权观看该直播</p>
            <span class="need-login" v-if="userId == 0">
              请先
              <i @click="goToLogin">登录></i>
            </span>
          </template>
          <!-- 已登录 -->
          <template v-if="userId != 0">
            <span class="check-area" v-if="!areaFlag" @click="checkTheArea">观看限制范围</span>
            <span class="forbid-area" v-else>不能观看的范围</span>
          </template>
        </div>
        <div class="forbid-content" v-if="areaFlag">
          <template v-for="(item, index) of limitInfo">
            <span :key="index" v-if="index < 16">{{ item.name }} &nbsp;&nbsp;</span>
          </template>
          <span class="check-more-btn" v-if="limitInfo.length > 17" @click="dialogVisible">更多></span>
        </div>
      </div>
    </div>
    <!-- 直播密码框 -->
    <template v-else-if="passwordFlag">
      <codeDom class="frosted-glass" :liveId="+liveId" @checkFlag="checkFlag">{{
          liveOptions.teachername || liveOptions.user_name
      }}</codeDom>
    </template>
    <!-- 视频播放器 -->
    <template v-else>
      <!-- <flvPlayer
        id="flvPlayer1"
        v-if="playerOption.url && !webrtc"
        :playerOption.sync="playerOption"
      ></flvPlayer>
      <webRtcPlayer
        v-else-if="webrtc"
        :url="webrtcOption.url"
        :uid="`${Math.random()}`"
      ></webRtcPlayer> -->
      <liveDPlayer :live_Options="liveOptions"></liveDPlayer>
    </template>
    <el-dialog title="不能观看的范围" class="areaDialog" :visible.sync="dialogVisible" width="550px">
      <span v-for="(item, index) of limitInfo" :key="index">{{ item.name }} &nbsp;&nbsp;</span>
    </el-dialog>
  </div>
</template>
<script>
import webRtcPlayer from "@/components/common/webrtcPlayer"
import flvPlayer from "@/components/common/flvPlayer"
import codeDom from "@/components/homepage/course/livePlayer/pass-code"
import { setInterval } from "timers"
import liveDPlayer from "./liveDPlayer.vue"
export default {
  components: {
    liveDPlayer,
    // flvPlayer,
    codeDom,
    webRtcPlayer,
  },
  props: {
    liveOptions: {
      type: Object,
      required: true,
      default() {
        return {}
      },
    },
  },
  data() {
    return {
      userId: this.$g.user_id, //用户id
      playerOption: {
        type: "flv",
        url: "",
        status_stream: true,
        status_stream_audio: true,
      },
      webrtcOption: {
        url: "",
      },
      limitInfo: [], //被限制的具体信息数据
      passwordFlag: false, //密码输入框
      areaFlag: false, //查看范围详情信息
      dialogVisible: false, //查看更多限制弹窗
      isLimitFlag: false, //限制条件框
      checkingInterval22: null, //检测直播是否结束
    }
  },
  created() {
    //设置计时器检查直播是否被删除
    if (this.checkingInterval22) {
      clearInterval(this.checkingInterval22._id)
    }
    this.checkingInterval22 = setInterval(this.checkLiveEnd, 10000)
  },
  computed: {
    isLimit() {
      return this.isLimitFlag || this.passwordFlag
    },
    webrtc() {
      return this.$store.getters.isSupportWebRtc
    },
    allownine() {
      return this.$store.getters.isAllowNine
    },
  },
  watch: {
    liveOptions: {
      handler(newVal, oldVal) {
        this.getData(newVal)
      },
      deep: true,
    },
    isLimit: {
      handler(newVal, oldVal) {
        this.$emit("isLimit", newVal)
      },
      immediate: true,
    },
  },
  mounted() {
    this.getData(this.liveOptions)
  },
  beforeDestroy() {
    if (this.checkingInterval22) {
      clearInterval(this.checkingInterval22._id)
    }
    this.checkingInterval22 = null
  },
  methods: {
    getData(res) {
      // 如果直播不是进行中状态的就不显示
      if (res._status != 2) {
        return
      }
      this.liveId = res.id //大直播id
      // 如果权限和密码都不设置
      if (res.limit_type == 0 && res.password == "") {
        this.showThePlayer(res)
        return
      }
      // 验证：
      if (this.userId == 0) {
        //用户没有登录

        if (res.password == "") {
          this.showThePlayer(res)
        } else {
          this.isLimitFlag = false
          this.dialogVisible = false
          this.passwordFlag = true //显示密码输入框
        }
      } else {
        // 用户已登录

        // 若视频设置了限制，显示权限弹框
        if (res.limit_type != 0) {
          this.isLimitFlag = true
          this.checkUserLimit(this.liveId)
        } else {
          //没被限制权限，则检查密码的情况
          this.checkLivePass(res)
        }
      }
    },
    // 没有限制，显示直播播放器
    showThePlayer(res) {
      let userAgent = navigator.userAgent
      if (userAgent.indexOf("Firefox") > -1) {
        let num = userAgent
          .toLowerCase()
          .match(/firefox\/([\d.]+)/)[1]
          .split(".")[0]
        if (num < 74) {
          this.$message.warning(
            `当前浏览器版本为火狐${num}，请升级到74版本以上`
          )
        }
      }

      this.isLimitFlag = false //关闭权限限制框
      this.dialogVisible = false //关闭权限限制详情弹窗
      this.playerOption.url = res.play_url //赋值播放流地址
      this.playerOption.status_stream = res.status_stream == "1" //赋值播放流画面是否开启
      this.playerOption.status_stream_audio = res.status_stream_audio == "1" //赋值播放流音频是否开启

      this.webrtcOption.url = res.webrtc_url
    },
    //检用户的观看权限
    checkUserLimit(liveId) {
      let success = (res) => {
        // 若被限制，提示用户他被禁止观看，并显示限制范围具体信息
        if (res.data == "no") {
          this.$message.warning("你已被限制观看")
          this.getLimitArea(liveId)
        } else {
          //没被限制权限，则检查密码的情况
          this.checkLivePass(this.liveOptions)
        }
      }
      this.$ajax({
        url: "api/live/get_islimit_by_live_user_id",
        method: "get",
        params: {
          live_id: liveId,
          user_id: this.userId,
        },
        func: {
          success: success,
        },
      })
    },
    //获取直播限制范围信息用于展示
    getLimitArea(liveId) {
      let success = (res) => {
        this.limitInfo = res.data
      }
      this.$ajax({
        url: "api/live/get_live_limit",
        method: "get",
        params: {
          live_id: liveId,
        },
        func: {
          success: success,
        },
      })
    },
    //检查当前直播，用户之前是否输入过正确的密码
    checkLivePass(liveData) {
      let success = (res) => {
        let livePass = res.data.userinfo.live_pass + "" //直播id字符串，用户曾看过，且输入过正确密码的
        let flag = livePass.split(",").indexOf(liveData.id + "")

        if (liveData.password == "" || flag > -1) {
          this.showThePlayer(liveData)
        } else {
          this.isLimitFlag = false
          this.dialogVisible = false
          this.passwordFlag = true //显示密码输入框
        }
      }
      this.$ajax({
        url: "api/login/new_login",
        method: "get",
        params: {},
        func: {
          success: success,
        },
      })
    },
    //查看限制范围的详情
    checkTheArea() {
      this.areaFlag = true
    },
    //去登录
    goToLogin() {
      let host_addr = sessionStorage.getItem("host_addr")
      window.location.href = host_addr + "/index/login/index"
    },
    //验证密码是否正确
    checkFlag(flag) {
      if (flag) {
        this.passwordFlag = false
        this.showThePlayer(this.liveOptions)
      }
    },
    // 检测直播是否被删除：
    checkLiveEnd() {
      if (!this.liveId) return
      let success = (res) => { }
      let fail = (res) => {
        this.$message.warning("直播已结束")
        clearInterval(this.checkingInterval22)
        this.$emit("isLiveEnd", true)
      }
      this.$ajax({
        url: "api/live/check_is_liveend",
        method: "get",
        params: {
          liveid: this.liveId,
        },
        func: {
          success: success,
          fail: fail,
        },
      })
    },
  },
}
</script>
<style lang="scss">
.home-live-player {
  height: 100%;
  background-color: #000;

  .unlogin-box {
    display: inline-block;
    width: 100%;
    height: 100%;
    text-align: center;
    background-color: rgba(0, 0, 0, 0.9);
    position: relative;

    .unlogin-container {
      display: inline-block;
      width: 644px;
      height: 400px;
      position: absolute;
      top: 50%;
      left: 50%;
      margin-top: -200px;
      margin-left: -322px;
    }

    .limit-tips {
      margin-top: 40px;
      font-size: 16px;

      .need-login {
        color: #909eaf;

        i {
          color: #348efc;
          padding-left: 10px;
        }
      }

      .not-allow {
        font-size: 18px;
        color: #b9d9ff;
        line-height: 24px;
        margin: 26px 0 38px;
      }

      .check-area {
        color: #348efc;
        cursor: pointer;
        line-height: 21px;
      }

      .forbid-area {
        color: #909eaf;
        line-height: 21px;
      }
    }

    .forbid-content {
      padding: 20px 0 0;
      text-align: center;

      span {
        margin-left: 5px;
        font-size: 16px;
        color: #fff;
        line-height: 21px;
      }

      .check-more-btn {
        color: #348efc;
        cursor: pointer;
      }
    }
  }
}
</style>
